'''
rgeDialogs - for the Random Game Generator project
By Doctus (kirikayuumura.noir@gmail.com)

Design inspired by Django Forms.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
'''

import os, os.path
import rgeMap
import rgeSystem
import rgeSave
import rgeModule, rgeTileset, rgeScene
import rgeViews
from rgeSystem import fake, translate, showErrorMessage, findFiles, findFolders, MODULE_DIR, RAWDATA_DIR, SCENE_DIR, IMAGE_EXTENSIONS, MODULE_EXTENSION, SCENE_EXTENSION, SPRITE_EXTENSION, TILESET_DIR, PORTRAIT_DIR, SAVE_DIR, SPRITE_DIR, makePortableFilename, ACTOR_DIR, ACTOR_EXTENSION
from rgeFields import integerField, floatField, stringField, dropDownField, sliderField, validationError
from rgeJson import *
from PyQt4 import QtGui, QtCore

class dialog(object):
    """A base class for dialogs.

    """

    def __init__(self):
        """Initializes the dialog, with optional parameters."""
        self.cleanData = None
        self._error = None

    def clean(self):
        """Check for errors and return well-formatted data."""
        raise NotImplementedError()

    @property
    def error(self):
        """Access any errors on this dialog."""
        self.is_valid()
        return self._error

    def is_valid(self):
        """Return true if the data is valid and complete."""
        try:
            self.clean()
            assert(self.cleanData is not None)
            return True
        except validationError as e:
            self.cleanData = None
            if len(e.args) > 0:
                self._error = e.args[0]
            else:
                # Catch-all shouldn't be seen by end-users
                self._error = translate('dialog', "There is an error in your input.")

    def save(self):
        """Utilize validated data to make changes."""
        raise NotImplementedError()

class resizeDialog(QtGui.QDialog):

    def __init__(self, origx, origy, currw, currh):
        QtGui.QDialog.__init__(self)
        self.owlabel = QtGui.QLabel("Current Width:")
        self.ohlabel = QtGui.QLabel("Current Height:")
        self.owlabel2 = QtGui.QLabel(str(origx))
        self.ohlabel2 = QtGui.QLabel(str(origy))
        self.setWindowTitle("Resize Pog")

        self.wlabel = QtGui.QLabel("New Width:")
        self.hlabel = QtGui.QLabel("New Height:")

        self.wBox = QtGui.QSpinBox()
        self.hBox = QtGui.QSpinBox()
        self.wBox.setRange(1, 1000)
        self.hBox.setRange(1, 1000)
        self.wBox.setValue(currw)
        self.hBox.setValue(currh)

        self.okButton = QtGui.QPushButton("Ok")
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.okButton.clicked.connect(self.okPressed)
        self.cancelButton.clicked.connect(self.cancelPressed)

        self.layout = QtGui.QGridLayout()
        self.layout.addWidget(self.owlabel, 0, 0)
        self.layout.addWidget(self.ohlabel, 1, 0)
        self.layout.addWidget(self.owlabel2, 0, 1)
        self.layout.addWidget(self.ohlabel2, 1, 1)

        self.layout.addWidget(self.wlabel, 2, 0)
        self.layout.addWidget(self.hlabel, 3, 0)
        self.layout.addWidget(self.wBox, 2, 1)
        self.layout.addWidget(self.hBox, 3, 1)
        self.layout.addWidget(self.okButton, 4, 0)
        self.layout.addWidget(self.cancelButton, 4, 1)
        self.setLayout(self.layout)

    def okPressed(self, checked):
        self.done(1)

    def cancelPressed(self, checked):
        self.done(0)

class newModuleDialog(dialog):
    '''dialog for creating a new module'''

    def __init__(self, parent):
        """Initializes the dialog data."""
        super(newModuleDialog, self).__init__()


        self.Name = "Module"



        def okayPressed():
            if self.nameBox.text().isEmpty() == False:
                OtherMods = findFolders(os.path.abspath(MODULE_DIR).replace('\\', '/'))
                ModExists = False
                for greatJustice in OtherMods:
                    if greatJustice == self.Name:
                        ModExists = True
                if ModExists:
                    showErrorMessage("Module with that name already exists")
                else:
                   self.widget.accept()

        self.widget = QtGui.QDialog(parent)
        self.okayButton = QtGui.QPushButton("Okay")
        self.okayButton.setDefault(True)
        self.cancelButton = QtGui.QPushButton("Cancel")
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.nameLabel = QtGui.QLabel("New Module Name:")
        self.nameBox = QtGui.QLineEdit()
        self.nameBox.textChanged.connect(self.setName)


        self.mainLayout = QtGui.QGridLayout()


        self.mainLayout.addWidget(self.nameLabel,0,0)
        self.mainLayout.addWidget(self.nameBox,0,1)
        self.mainLayout.addWidget(self.okayButton,1,0)
        self.mainLayout.addWidget(self.cancelButton,1,1)


        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Choose New Module Name")

    def setName(self, newName):
        self.Name = newName

    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)

class gfxSettingsDialog(dialog):
    """A dialog used to create a new map."""

    def __init__(self, **kwargs):
        """Initializes the dialog data."""
        super(gfxSettingsDialog, self).__init__()
        self.fields = self._createFields(kwargs)

    def _createFields(self, data):
        """Create the fields used by this dialog."""
        self.fieldtemp = ["GL_COMPRESSED_RG_RGTC2", 1.0, "GL_NEAREST", "GL_NEAREST", "GL_NEAREST_MIPMAP_NEAREST", 1, 1, "Magic", "Off"]

        try:
            js = jsonload(os.path.join(SAVE_DIR, "gfx_settings.rgs"))
            self.fieldtemp[0] = loadString('gfx.compress', js.get('compress'))
            self.fieldtemp[1] = loadFloat('gfx.anifilt', js.get('anifilt'))
            self.fieldtemp[2] = loadString('gfx.minfilter', js.get('minfilter'))
            self.fieldtemp[3] = loadString('gfx.magfilter', js.get('magfilter'))
            self.fieldtemp[4] = loadString('gfx.mipminfilter', js.get('mipminfilter'))
            self.fieldtemp[5] = loadString('gfx.FSAA', js.get('FSAA'))
            self.fieldtemp[6] = loadString('gfx.VBO', js.get('VBO'))
            self.fieldtemp[7] = loadString('gfx.magic', js.get('Magic'))
        except:
            print "no settings detected"
            pass

        try:
            self.fieldtemp[8] = loadString('gfx.splash', js.get('Scene'))
        except:
            pass

        normFilters = ["GL_NEAREST", "GL_LINEAR"]
        mipFilters = ["Off", "GL_NEAREST_MIPMAP_NEAREST", "GL_NEAREST_MIPMAP_LINEAR", "GL_LINEAR_MIPMAP_NEAREST", "GL_LINEAR_MIPMAP_LINEAR"]

        return dict(
            compress=dropDownField(translate('gfxSettingsDialog', 'Compress'), ["None", "GL_COMPRESSED_RG_RGTC2"],
                value=data.get('compress', self.fieldtemp[0])),
            anifilt=floatField(translate('gfxSettingsDialog', 'Anifilt'),
                min=1.0, max=16.0, decimals=1, value=data.get('Anifilt', self.fieldtemp[1])),
            minfilter=dropDownField(translate('gfxSettingsDialog', 'minfilter'), normFilters,
                value=data.get('minfilter', self.fieldtemp[2])),
            magfilter=dropDownField(translate('gfxSettingsDialog', 'magfilter'), normFilters,
                value=data.get('magfilter', self.fieldtemp[3])),
            mipminfilter=dropDownField(translate('gfxSettingsDialog', 'mipminfilter'), mipFilters,
                value=data.get('mipminfilter', self.fieldtemp[4])),
            FSAA=dropDownField(translate('gfxSettingsDialog', 'FSAA'), ["Off", "On"],
                value=data.get('FSAA', self.fieldtemp[5])),
            VBO=dropDownField(translate('gfxSettingsDialog', 'VBO'), ["Off", "On"],
                value=data.get('VBO', self.fieldtemp[6])),
            Magic=dropDownField(translate('gfxSettingsDialog', 'Magic'), ["Magic", "More Magic"],
                value=data.get('Magic', self.fieldtemp[7])),
            Scene=dropDownField(translate('gfxSettingsDialog', 'Scene'), ["Off", "On"],
                value=data.get('Scene', self.fieldtemp[8])))

    def _interpretFields(self, fields):
        """Interpret the fields into a dictionary of clean items."""
        return dict((key, field.clean()) for key, field in fields.items())

    def exec_(self, parent, accept):
        """Executes this dialog as modal, ensuring OK is only hit with valid data.

        parent -- the parent object of this dialog
        accept() -- Acceptance function;
            return True to accept data, False to continue (you should show an error)

        returns: True if the OK button is hit and the acceptance function passes.

        """

        widget = QtGui.QDialog(parent)

        # Buttons
        okayButton = QtGui.QPushButton(translate('gfxSettingsDialog', "Save"))
        okayButton.setDefault(True)
        cancelButton = QtGui.QPushButton(translate('gfxSettingsDialog', "Cancel"))

        # Add fields
        formLayout = QtGui.QFormLayout()
        for id in ('compress', 'anifilt', 'minfilter', 'magfilter', 'mipminfilter', 'FSAA', 'VBO', 'Magic', 'Scene'):
            field = self.fields[id]
            formLayout.addRow(translate('gfxSettingsDialog', '{0}: ', 'Row layout').format(field.name), field.widget(widget))

        # Add buttons
        theLesserOrFalseBox = QtGui.QBoxLayout(0)
        theLesserOrFalseBox.addWidget(okayButton)
        theLesserOrFalseBox.addWidget(cancelButton)

        # Position both
        grandBox = QtGui.QBoxLayout(2)
        grandBox.addLayout(formLayout)
        grandBox.addLayout(theLesserOrFalseBox)

        # Set up the widget
        widget.setLayout(grandBox)
        widget.setModal(True)
        widget.setWindowTitle(translate('gfxSettingsDialog', "Configure Graphics"))

        # Allow user to specify validation
        def okayPressed():
            if accept():
                widget.accept()

        # Signals
        widget.connect(okayButton, QtCore.SIGNAL('clicked()'), okayPressed)
        widget.connect(cancelButton, QtCore.SIGNAL('clicked()'), widget.reject)

        # Show to user
        return (widget.exec_() == QtGui.QDialog.Accepted)

    def clean(self):
        """Check for errors and return well-formatted data."""
        self.cleanData = self._interpretFields(self.fields)
        return self.cleanData

    def save(self):
        """Make a new map and return it."""
        assert(self.cleanData)
        return self._interpretFields(self.fields)

class chooseMapTilemapDialog(dialog):
    """dialog for choosing map tilemaps"""

    def __init__(self, parent):
        """Initializes the dialog data."""
        super(chooseMapTilemapDialog, self).__init__()

        self.widget = QtGui.QDialog(parent)
        self.okayButton = QtGui.QPushButton("Okay")
        self.cancelButton = QtGui.QPushButton("Cancel")
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.widget.accept)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.layerArea = QtGui.QListWidget(parent)
        self.mainLayout = QtGui.QGridLayout()

        self.tilesets = findFiles(TILESET_DIR, '*' + TILESET_EXTENSION)
        self.tilesets.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
        for greatJustice in self.tilesets:
            icon = QtGui.QIcon(os.path.join(LAYER_DIR, greatJustice))
            self.layerArea.addItem(QtGui.QListWidgetItem(icon, greatJustice))

        self.mainLayout.addWidget(self.layerArea,0,0)
        self.mainLayout.addWidget(self.okayButton,1,0)
        self.mainLayout.addWidget(self.cancelButton,1,1)


        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Choose Tilemap")


    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)


class newTilesetDialog(dialog):
    """dialog for chosing and naming image files for tilemaps"""

    def __init__(self, parent, fileFolder):
        """init"""
        super(newTilesetDialog, self).__init__()

        self.name = None
        self.filename = None
        self.fileFolder = fileFolder

        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)
        self.tilemapLabel = QtGui.QLabel("Name:")
        self.tilemapNameBox = QtGui.QLineEdit()
        self.tilemapNameBox.setEnabled(False)
        self.tilemapOpenButton = QtGui.QPushButton("Load Image")
        self.okayButton = QtGui.QPushButton("Okay")
        self.okayButton.setEnabled(False)
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.tilemapNameBox.textChanged.connect(self.setName)
        self.tilemapOpenButton.clicked.connect(self.openDialog)
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.mainLayout.addWidget(self.tilemapOpenButton,0,0)
        self.mainLayout.addWidget(self.tilemapLabel,1,0)
        self.mainLayout.addWidget(self.tilemapNameBox,1,1)
        self.mainLayout.addWidget(self.okayButton,2,0)
        self.mainLayout.addWidget(self.cancelButton,2,1)


        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Load tileset")



    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)


    def setName(self,NewName):
        self.name = NewName
        if NewName is "":
            self.okayButton.setEnabled(False)
        else:
            self.okayButton.setEnabled(True)

    def openDialog(self):
        self.filename = rgeSystem.promptLoadFile("Load Image", '*' + IMAGE_EXTENSIONS,RAWDATA_DIR)
        if not self.filename:
            return
        self.tilemapNameBox.setEnabled(True)
        TempName = os.path.basename(self.filename)
        if TempName.endswith('.png'):
            TempName = TempName[:-4]
        self.setName(os.path.basename(TempName))
        if self.tilemapNameBox.text().isEmpty():
            self.tilemapNameBox.setText(self.name)


    def okayPressed(self):
        if self.tilemapNameBox.text().isEmpty() == False:
            OtherTexts = findFiles(self.fileFolder + TILESET_DIR, '*' + IMAGE_EXTENSIONS)
            TextExists = False
            for greatJustice in OtherTexts:
                if greatJustice == self.name + IMAGE_EXTENSIONS:
                    TextExists = True
            if TextExists:
                showErrorMessage("Tileset with that name already exists")
                return
            self.widget.accept()

class newSceneDialog(dialog):
    """dialog for making new scenes"""

    def __init__(self, parent, fileFolder):
        """init"""
        super(newSceneDialog, self).__init__()

        self.name = None
        self.fileFolder = fileFolder


        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)
        self.splashLabel = QtGui.QLabel("Name:")
        self.splashNameBox = QtGui.QLineEdit()
        self.okayButton = QtGui.QPushButton("Okay")
        self.okayButton.setEnabled(False)
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.splashNameBox.textChanged.connect(self.setName)
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.mainLayout.addWidget(self.splashLabel,0,0)
        self.mainLayout.addWidget(self.splashNameBox,0,1)
        self.mainLayout.addWidget(self.okayButton,1,0)
        self.mainLayout.addWidget(self.cancelButton,1,1)


        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Load scene")

    def setName(self,NewName):
        self.name = NewName
        if NewName is "":
            self.okayButton.setEnabled(False)
        else:
            self.okayButton.setEnabled(True)

    def okayPressed(self):
        if self.splashNameBox.text().isEmpty() == False:
            OtherTexts = findFiles(self.fileFolder + SCENE_DIR, '*' + SCENE_EXTENSION)
            TextExists = False
            for greatJustice in OtherTexts:
                if greatJustice == self.name + SCENE_EXTENSION:
                    TextExists = True
            if TextExists:
                showErrorMessage("Scene with that name already exists")
                return
            self.widget.accept()

    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)

class newSpriteDialog(dialog):
    """dialog for making new scenes"""

    def __init__(self, parent, fileFolder):
        """init"""
        super(newSpriteDialog, self).__init__()

        self.name = None
        self.fileFolder = fileFolder


        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)
        self.splashLabel = QtGui.QLabel("Name:")
        self.splashNameBox = QtGui.QLineEdit()
        self.okayButton = QtGui.QPushButton("Okay")
        self.okayButton.setEnabled(False)
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.splashNameBox.textChanged.connect(self.setName)
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.mainLayout.addWidget(self.splashLabel,0,0)
        self.mainLayout.addWidget(self.splashNameBox,0,1)
        self.mainLayout.addWidget(self.okayButton,1,0)
        self.mainLayout.addWidget(self.cancelButton,1,1)


        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Load sprite")

    def setName(self,NewName):
        self.name = NewName
        if NewName is "":
            self.okayButton.setEnabled(False)
        else:
            self.okayButton.setEnabled(True)

    def okayPressed(self):
        if self.splashNameBox.text().isEmpty() == False:
            OtherTexts = findFiles(self.fileFolder + SPRITE_DIR, '*' + SPRITE_EXTENSION)
            TextExists = False
            for greatJustice in OtherTexts:
                if greatJustice == self.name + SPRITE_EXTENSION:
                    TextExists = True
            if TextExists:
                showErrorMessage("Sprite with that name already exists")
                return
            self.widget.accept()

    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)

class newActorDialog(dialog):
    """dialog for making new actors"""

    def __init__(self, parent, fileFolder):
        """init"""
        super(newActorDialog, self).__init__()

        self.name = None
        self.fileFolder = fileFolder


        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)
        self.splashLabel = QtGui.QLabel("Name:")
        self.splashNameBox = QtGui.QLineEdit()
        self.okayButton = QtGui.QPushButton("Okay")
        self.okayButton.setEnabled(False)
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.splashNameBox.textChanged.connect(self.setName)
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.mainLayout.addWidget(self.splashLabel,0,0)
        self.mainLayout.addWidget(self.splashNameBox,0,1)
        self.mainLayout.addWidget(self.okayButton,1,0)
        self.mainLayout.addWidget(self.cancelButton,1,1)


        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Load actor")

    def setName(self,NewName):
        self.name = NewName
        if NewName is "":
            self.okayButton.setEnabled(False)
        else:
            self.okayButton.setEnabled(True)

    def okayPressed(self):
        if self.splashNameBox.text().isEmpty() == False:
            OtherTexts = findFiles(self.fileFolder + ACTOR_DIR, '*' + ACTOR_EXTENSION)
            TextExists = False
            for greatJustice in OtherTexts:
                if greatJustice == self.name + ACTOR_EXTENSION:
                    TextExists = True
            if TextExists:
                showErrorMessage("Actor with that name already exists")
                return
            self.widget.accept()

    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)


class newTextureDialog(dialog):
    """dialog for chosing and naming image files for sprites"""

    def __init__(self, parent, fileFolder):
        """init"""
        super(newTextureDialog, self).__init__()

        self.name = None
        self.filename = None
        self.fileFolder = fileFolder

        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)
        self.tilemapLabel = QtGui.QLabel("Name:")
        self.tilemapNameBox = QtGui.QLineEdit()
        self.tilemapNameBox.setEnabled(False)
        self.tilemapOpenButton = QtGui.QPushButton("Load Image")
        self.okayButton = QtGui.QPushButton("Okay")
        self.okayButton.setEnabled(False)
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.tilemapNameBox.textChanged.connect(self.setName)
        self.tilemapOpenButton.clicked.connect(self.openDialog)
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.mainLayout.addWidget(self.tilemapOpenButton,0,0)
        self.mainLayout.addWidget(self.tilemapLabel,1,0)
        self.mainLayout.addWidget(self.tilemapNameBox,1,1)
        self.mainLayout.addWidget(self.okayButton,2,0)
        self.mainLayout.addWidget(self.cancelButton,2,1)


        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Load texture")



    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)


    def setName(self,NewName):
        self.name = NewName
        if NewName is "":
            self.okayButton.setEnabled(False)
        else:
            self.okayButton.setEnabled(True)

    def openDialog(self):
        self.filename = rgeSystem.promptLoadFile("Load Image", '*' + IMAGE_EXTENSIONS,RAWDATA_DIR)
        if not self.filename:
            return
        self.tilemapNameBox.setEnabled(True)
        TempName = os.path.basename(self.filename)
        if TempName.endswith('.png'):
            TempName = TempName[:-4]
        self.setName(os.path.basename(TempName))
        if self.tilemapNameBox.text().isEmpty():
            self.tilemapNameBox.setText(self.name)


    def okayPressed(self):
        if self.tilemapNameBox.text().isEmpty() == False:
            self.widget.accept()

class sceneLoadTilesetDialog(dialog):
    """dialog for loading assets"""

    def __init__(self, parent, fileFolder, fileType):
        """init"""
        super(sceneLoadTilesetDialog, self).__init__()

        self.parent = parent
        self.fileFolder = fileFolder
        self.fileType = fileType
        self.tilemap = None
        self.x = 1
        self.y = 1

        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)

        self.nameLabel = QtGui.QLabel("Name:")
        self.tilesetLabel = QtGui.QLabel("")
        self.xLabel = QtGui.QLabel("Width:")
        self.yLabel = QtGui.QLabel("Height:")
        self.sizeLabel = QtGui.QLabel("Map Size (pixels):")
        self.sizeDisplayLabel = QtGui.QLabel("")
        self.xWidthBox = QtGui.QSpinBox()
        self.yHeightBox = QtGui.QSpinBox()
        self.pickTilesetButton = QtGui.QPushButton("Load Tileset")
        self.okayButton = QtGui.QPushButton("Okay")
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.xWidthBox.setRange(1,2000)
        self.yHeightBox.setRange(1,2000)
        self.xWidthBox.setValue(1)
        self.yHeightBox.setValue(1)
        self.xWidthBox.setEnabled(False)
        self.yHeightBox.setEnabled(False)
        self.okayButton.setEnabled(False)

        self.pickTilesetButton.clicked.connect(self.findTileset)
        self.xWidthBox.valueChanged.connect(self.xChanged)
        self.yHeightBox.valueChanged.connect(self.yChanged)
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.mainLayout.addWidget(self.pickTilesetButton,0,0)
        self.mainLayout.addWidget(self.nameLabel,1,0)
        self.mainLayout.addWidget(self.tilesetLabel,1,1)
        self.mainLayout.addWidget(self.sizeLabel,2,0)
        self.mainLayout.addWidget(self.sizeDisplayLabel,2,1)
        self.mainLayout.addWidget(self.xLabel,3,0)
        self.mainLayout.addWidget(self.xWidthBox,3,1)
        self.mainLayout.addWidget(self.yLabel,4,0)
        self.mainLayout.addWidget(self.yHeightBox,4,1)
        self.mainLayout.addWidget(self.okayButton,5,0)
        self.mainLayout.addWidget(self.cancelButton,5,1)
        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Load tileset")

    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)

    def findTileset(self):
        Dialog = loadDataDialog(self.parent, self.fileFolder, self.fileType)
        if(Dialog.exec_()):
            self.tilemap = rgeViews.loadTileset(Dialog.selectedFile)
            self.xWidthBox.setEnabled(True)
            self.yHeightBox.setEnabled(True)
            self.okayButton.setEnabled(True)
            self.tilesetLabel.setText(self.tilemap.getName())
            self.calculateSize()

    def xChanged(self, NewValue):
        self.x = NewValue
        self.calculateSize()

    def yChanged(self, NewValue):
        self.y = NewValue
        self.calculateSize()

    def calculateSize(self):
        self.sizeDisplayLabel.setText(str(self.xWidthBox.value() * self.tilemap.getWidth()) + 'x' + str(self.yHeightBox.value() * self.tilemap.getHeight()))

    def okayPressed(self):
        if self.tilemap != None:
            self.widget.accept()


class setValueDialog(dialog):
    """dialog for setting values"""

    def __init__(self, parent, valueName, oldValue = 1, rangeMin = 1, rangeMax = 2000):
        """init"""
        super(setValueDialog, self).__init__()

        self.returnedValue = oldValue

        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)

        self.valueBox = QtGui.QSpinBox()
        self.okayButton = QtGui.QPushButton("Okay")
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.valueBox.setRange(rangeMin,rangeMax)
        self.valueBox.setValue(oldValue)

        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.mainLayout.addWidget(self.valueBox,0,0)
        self.mainLayout.addWidget(self.okayButton,1,0)
        self.mainLayout.addWidget(self.cancelButton,1,1)
        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Set " + valueName)

    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)

    def okayPressed(self):
        self.returnedValue = self.valueBox.value()
        self.widget.accept()


class setValueDialogFloat(setValueDialog):
    def __init__(self, parent, valueName, oldValue = 1, rangeMin = 0, rangeMax = 2000):
        """init"""
        super(setValueDialogFloat, self).__init__(parent, valueName, oldValue, rangeMin, rangeMax)
        self.valueBox.setDecimals(4)


class setExtraBaseDialog(dialog):
    def __init__(self, parent, keys):
        super(setExtraBaseDialog, self).__init__()

        self.keys = keys

        self.returnedExtra = None



class setExtraIntDialog(setExtraBaseDialog):
    def __init__(self, parent, keys, oldValue = 1, rangeMin = 0, rangeMax = 2000000000):
        super(setExtraIntDialog, self).__init__(parent, keys)

        self.key = ""
        self.value = oldValue

        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)

        self.keyBox = QtGui.QLineEdit()
        self.valueBox = QtGui.QSpinBox()
        self.valueBox.setRange(rangeMin, rangeMax)
        self.okayButton = QtGui.QPushButton("Okay")
        self.okayButton.setEnabled(False)
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.connect()
        self.okayButton.clicked.connect(self.okayPressed)
        self.cancelButton.clicked.connect(self.widget.reject)

        self.update()

        self.mainLayout.addWidget(self.keyBox,0,0)
        self.mainLayout.addWidget(self.valueBox,0,1)
        self.mainLayout.addWidget(self.okayButton,0,1)
        self.mainLayout.addWidget(self.cancelButton,1,1)
        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Set Value")

    def exec_(self):
        self.returnedExtra = IntItem(self.valueBox.value(), self.keyBox.text())
        return (self.widget.exec_() == QtGui.QDialog.Accepted)

    def connect(self):
        self.keyBox.textEdited.connect(self.update)
        self.valueBox.valueChanged.connect(self.update)

    def disconnect(self):
        self.keyBox.textEdited.disconnect(self.update)
        self.valueBox.valueChanged.disconnect(self.update)

    def update(self):
        if len(self.key) > 0 and not self.key in self.keys:
            self.okayButton.setEnabled(True)
        else:
            self.okayButton.setEnabled(False)



class loadDataDialog(dialog):
    """dialog for loading assets"""

    def __init__(self, parent, fileFolder, fileType):
        """init"""
        super(loadDataDialog, self).__init__()

        self.selectedFile = None

        self.mainLayout = QtGui.QGridLayout()
        self.widget = QtGui.QDialog(parent)

        self.itemList = QtGui.QListWidget()
        self.okayButton = QtGui.QPushButton("Okay")
        self.cancelButton = QtGui.QPushButton("Cancel")

        self.itemList.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
        self.okayButton.setEnabled(False)

        Items = findFiles(fileFolder, fileType)
        for greatJustice in Items:
            Path = fileFolder + '/' + greatJustice
            Name = rgeSave.getName(Path)
            Icon = QtGui.QIcon(Path)
            AddedItem = QtGui.QListWidgetItem(Icon,Name,self.itemList,1)
            AddedItem.setToolTip(Path)
            #self.itemList.addItem(AddedItem)

        self.itemList.itemSelectionChanged.connect(self.allowOpen)
        self.widget.connect(self.okayButton, QtCore.SIGNAL('clicked()'), self.okayPressed)
        self.widget.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.widget.reject)

        self.mainLayout.addWidget(self.itemList,0,0)
        self.mainLayout.addWidget(self.okayButton,1,0)
        self.mainLayout.addWidget(self.cancelButton,1,1)

        self.widget.setLayout(self.mainLayout)
        self.widget.setWindowTitle("Load Something")

    def exec_(self):
        return (self.widget.exec_() == QtGui.QDialog.Accepted)

    def okayPressed(self):
        self.selectedFile = self.itemList.currentItem().toolTip()
        self.widget.accept()

    def allowOpen(self):
        if len(self.itemList.selectedItems()) <= 0:
            self.okayButton.setEnabled(False)
        else:
            self.okayButton.setEnabled(True)